'use strict'

const mpkey = require('../../config/mpkey.js')
const {httpcli} = require('gohttp')

class mplogin {

  constructor () {
    //param默认就是/:id，若要改变路由，则可以设置此属性，比如设置为/:name
    this.param = '/:code'
  }

  /**
   * 创建资源
   * @param {context} c
   * @returns 
   */
  async get (c) {
    //获取小程序端wx.login获取的授权登录码
    let code = c.param.code

    let url = `https://api.weixin.qq.com/sns/jscode2session`
              + `?js_code=${code}`
              + `&appid=${mpkey.appid}&secret=${mpkey.secret}`
              + `&grant_type=authorization_code`

    //发起请求获取用户信息。
    let ret = await httpcli.get(url)

    if (!ret.ok) {
      return c.status(500).send('request failed.')
    }

    let r = ret.json()

    //请求失败，返回错误信息
    if (r.errcode) {
      return c.status(400).send(r.errmsg)
    }

    //返回加密后的值
    let data = {
      rand: Math.random(),
      openid: r.openid,
      //客户端IP地址
      ip: c.ip,
      ua: c.headers['user-agent'] || ''
    }

    //签发token
    let token = c.service.tok.make(data)

    //如果已经登陆，更新时间，如果没有登录，加入数据
    c.body.update_time = c.body.create_time = Date.now()
    c.body.openid = r.openid
    c.body.code = code
    let u = await c.service.users
            .where('openid',r.openid)
            .get(['openid'])
    //console.log(c.body)
    if(u){
      u = await c.service.users
          .where('openid',r.openid)
          .update({update_time:Date.now()})
    }else{
      u = await c.service.users.insert(c.body)
    }

    c.send(token)
  }

}

module.exports = mplogin
